/*
 * Copyright Eduardo Aponte 2013
 * aponteeduardo@gmail.com
 */
#include <eyelink.h>
#include "mex.h"
#include "utils.h"



INT16 _main( INT16 bs, char FARTYPE *ops )
{
    return open_eyelink_system(bs,ops); 
}


void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] )
{
    mwSize td[2] = {1,1};
    double *status;
    int i;
    /* Buffer size */
    int bs; 
    /* Matlab buffer: WARNING no protection against buffer over load */
    char *mb;
    /* Eyelink char. To support compatibility.*/
    char FARTYPE *elb;
    
    
    /* Verify input arguments. */
    if(nrhs != 2 ) {
        mexErrMsgTxt("Incorrect number of inputs.");
    } else if( nlhs > 1 ) {
        mexErrMsgTxt("Too many output arguments.");
    }
    
    if ( isscalar( *prhs ) ){
        INT16 scalar;
        /* Returns the scalar, casts to int if necessary. Returns 0 if */
        /* input is complex. */
        if ( returnscalar( *prhs, &bs ) != 1 )
            mexErrMsgTxt("Complex data is not supported.");                        
    } else {
        mexErrMsgTxt("bufsize should be a scalar."); 
    }
    
    if ( mxIsChar(prhs[1]) != 1)
      mexErrMsgTxt( "options must be a string.");
      
    mb  = mxArrayToString(prhs[1]);
    
    if(mb == NULL) 
      mexErrMsgTxt("Could not convert input to string.");
    
    bs  = (mxGetM(*prhs) * mxGetN(*prhs)) + 1;
    elb = mxCalloc(bs,sizeof(char FARTYPE));    
    
    for (i = 0; i < bs-1; i++)
        elb[i] = (char FARTYPE ) mb[i];
    
    plhs[0] = mxCreateNumericArray( 2, td, mxDOUBLE_CLASS, mxREAL);
    status = mxGetPr(plhs[0]);    
    status[0] = (double ) _main( (INT16 ) bs, elb );
    
    mxFree( elb );
    
    return;
    
}


